<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');

class Auth {
	private $CI;
	
	function Auth() {
		$this->CI = &get_instance();
	}
	
	function AuthByID($blogger_id, $pwd, $pwd_is_hash = TRUE) {
		$qry = $this->CI->db->query('SELECT * FROM `nt_bloggers` WHERE `id` = ?', array($blogger_id));
		if($qry->num_rows() < 1) {
			// no such blogger, return FALSE
			return FALSE;
		} else {
			// now check password
			$real_pwd = $pwd_is_hash ? md5($qry->row()->password) : $qry->row()->password;
			if(strcmp($real_pwd, $pwd) == 0) {
				// auth success
				return $qry->row();
			} else {
				// pwd error
				return FALSE;
			}
		}
	}
	
	function AuthByUserName($user_name, $pwd, $pwd_is_hash = TRUE) {
		$qry = $this->CI->db->query('SELECT * FROM `nt_bloggers` WHERE `user_name` = ?', array($user_name));
		if($qry->num_rows() < 1) {
			// no such user
			return FALSE;
		} else {
			$real_pwd = $qry->row()->password;
			if(strcmp($real_pwd, $pwd) == 0) {
				// Login OK! Just return this row...
				return $qry->row();
			} else {
				// pwd error!
				return FALSE;
			}
		}
	}
	
	function AuthFriendPassword($blogger_id, $friend_pwd_hash) {
		$qry = $this->CI->db->query('SELECT `friend_password` FROM `nt_blogger_info` WHERE `blogger_id` = ?', array($blogger_id));
		if($qry->num_rows() < 1) {
			return FALSE;
		}
		$fp_hash = md5($qry->row()->friend_password);
		if(strcmp($fp_hash, $friend_pwd_hash) == 0) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	// Below are old methods...
	
	// Login check, return TRUE or FALSE
	function Login($blogger_id, $pwd, $pwd_is_hash = TRUE) {
		$qry = $this->CI->db->query('SELECT `id`, `user_name`, `password` FROM `nt_bloggers` WHERE `id` = ?', array($blogger_id));
		if($qry->num_rows() < 1) {
			// no such user, return FALSE!
			return FALSE;
		} else {
			$real_pwd = $qry->row()->password;
			if($pwd_is_hash) {
				$real_pwd = md5($real_pwd);
			}
			if(strcmp($real_pwd, $pwd) == 0) {
				return TRUE;
			} else {
				return FALSE;
			}
		}
	}
	
	// Returns a whole User-Object or NULL
	function UserLogin($user_name, $pwd) {
		$qry = $this->CI->db->query('SELECT * FROM `nt_bloggers` WHERE `user_name` = ?', array($user_name));
		if($qry->num_rows() < 1) {
			// no such user
			return NULL;
		} else {
			$real_pwd = $qry->row()->password;
			if(strcmp($real_pwd, $pwd) == 0) {
				// Login OK! Just return this row...
				return $qry->row();
			} else {
				// Pwd error!
				return NULL;
			}
		}
	}
	
	function FriendLogin($blogger_id, $friend_pwd_hash) {
		$qry = $this->CI->db->query('SELECT `friend_password` FROM `nt_blogger_info` WHERE `blogger_id` = ?', array($blogger_id));
		if($qry->num_rows() < 1) {
			return FALSE;
		}
		$fp_hash = md5($qry->row()->friend_password);
		if(strcmp($fp_hash, $friend_pwd_hash) == 0) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
?>